package com.coder.algorithm.offer_2;

import java.util.Locale;

/**
 * 不用加减乘除做加法
 *
 * @author yuhushuan
 * @date 2020/7/4 11:00
 */
public class _65_AddTwoNumbers {
    private static int add(int num1, int num2) {
        // 半加
        int sum = num1 ^ num2;
        int carry = num1 & num2;
        while (carry != 0) {
            num1 = sum;
            num2 = carry << 1;

            sum = num1 ^ num2;
            carry = num1 & num2;
        }
        return sum;
    }

    public static void main(String[] args) {
        // 功能测试
        print(5, 10);
        print(1, 1);
        print(0, 0);

        print(15, 31);
        print(-15, -31);
    }

    private static void print(int num1, int num2) {
        System.out.println(String.format(Locale.getDefault(),
                "%d + %d = %d", num1, num2, add(num1, num2)));
    }
}
